<template>
  <el-dialog
    title="物模型配置"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="1200px"
    append-to-body
    @close="handleClose"
  >
    <el-tabs v-model="activeTab">
      <!-- 功能定义 -->
      <el-tab-pane label="功能定义" name="properties">
        <div class="tab-header">
          <el-button type="primary" @click="handleAddProperty">新增属性</el-button>
        </div>
        <el-table :data="properties" border style="width: 100%">
          <el-table-column prop="identifier" label="标识符" width="120" />
          <el-table-column prop="name" label="功能名称" width="120" />
          <el-table-column prop="dataType" label="数据类型" width="100">
            <template #default="scope">
              <el-tag :type="getDataTypeTag(scope.row.dataType)">{{ scope.row.dataType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="accessMode" label="读写类型" width="100">
            <template #default="scope">
              <el-tag :type="getAccessModeTag(scope.row.accessMode)">{{ getAccessModeText(scope.row.accessMode) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="range" label="数值范围" width="120" />
          <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="170" fixed="right">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEditProperty(scope.row)">编辑</el-button>
              <el-button link type="danger" size="small" @click="handleDeleteProperty(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 事件定义 -->
      <el-tab-pane label="事件定义" name="events">
        <div class="tab-header">
          <el-button type="primary" @click="handleAddEvent">新增事件</el-button>
        </div>
        <el-table :data="events" border style="width: 100%">
          <el-table-column prop="identifier" label="标识符" width="120" />
          <el-table-column prop="name" label="事件名称" width="120" />
          <el-table-column prop="eventType" label="事件类型" width="100">
            <template #default="scope">
              <el-tag :type="getEventTypeTag(scope.row.eventType)">{{ getEventTypeText(scope.row.eventType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="outputData" label="输出参数" min-width="200" show-overflow-tooltip />
          <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="170" fixed="right">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEditEvent(scope.row)">编辑</el-button>
              <el-button link type="danger" size="small" @click="handleDeleteEvent(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 服务定义 -->
      <el-tab-pane label="服务定义" name="services">
        <div class="tab-header">
          <el-button type="primary" @click="handleAddService">新增服务</el-button>
        </div>
        <el-table :data="services" border style="width: 100%">
          <el-table-column prop="identifier" label="标识符" width="120" />
          <el-table-column prop="name" label="服务名称" width="120" />
          <el-table-column prop="callType" label="调用方式" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.callType === 'async' ? 'success' : 'warning'">
                {{ scope.row.callType === 'async' ? '异步' : '同步' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="inputData" label="输入参数" min-width="150" show-overflow-tooltip />
          <el-table-column prop="outputData" label="输出参数" min-width="150" show-overflow-tooltip />
          <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="170" fixed="right">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEditService(scope.row)">编辑</el-button>
              <el-button link type="danger" size="small" @click="handleDeleteService(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">保 存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 属性编辑对话框 -->
  <el-dialog
    :title="propertyForm.id ? '编辑属性' : '新增属性'"
    v-model="propertyDialogVisible"
    width="600px"
    append-to-body
  >
    <el-form ref="propertyFormRef" :model="propertyForm" :rules="propertyRules" label-width="100px">
      <el-form-item label="标识符" prop="identifier">
        <el-input v-model="propertyForm.identifier" placeholder="请输入标识符" />
      </el-form-item>
      <el-form-item label="功能名称" prop="name">
        <el-input v-model="propertyForm.name" placeholder="请输入功能名称" />
      </el-form-item>
      <el-form-item label="数据类型" prop="dataType">
        <el-select v-model="propertyForm.dataType" placeholder="请选择数据类型" style="width: 100%">
          <el-option label="整数" value="int" />
          <el-option label="浮点数" value="float" />
          <el-option label="布尔" value="bool" />
          <el-option label="字符串" value="text" />
          <el-option label="枚举" value="enum" />
          <el-option label="日期" value="date" />
        </el-select>
      </el-form-item>
      <el-form-item label="读写类型" prop="accessMode">
        <el-select v-model="propertyForm.accessMode" placeholder="请选择读写类型" style="width: 100%">
          <el-option label="只读" value="r" />
          <el-option label="只写" value="w" />
          <el-option label="读写" value="rw" />
        </el-select>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="propertyForm.unit" placeholder="请输入单位" />
      </el-form-item>
      <el-form-item label="数值范围" prop="range">
        <el-input v-model="propertyForm.range" placeholder="例如：0-100" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="propertyForm.description" type="textarea" :rows="3" placeholder="请输入描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="propertyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveProperty">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 事件编辑对话框 -->
  <el-dialog
    :title="eventForm.id ? '编辑事件' : '新增事件'"
    v-model="eventDialogVisible"
    width="600px"
    append-to-body
  >
    <el-form ref="eventFormRef" :model="eventForm" :rules="eventRules" label-width="100px">
      <el-form-item label="标识符" prop="identifier">
        <el-input v-model="eventForm.identifier" placeholder="请输入标识符" />
      </el-form-item>
      <el-form-item label="事件名称" prop="name">
        <el-input v-model="eventForm.name" placeholder="请输入事件名称" />
      </el-form-item>
      <el-form-item label="事件类型" prop="eventType">
        <el-select v-model="eventForm.eventType" placeholder="请选择事件类型" style="width: 100%">
          <el-option label="信息" value="info" />
          <el-option label="告警" value="alert" />
          <el-option label="故障" value="error" />
        </el-select>
      </el-form-item>
      <el-form-item label="输出参数" prop="outputData">
        <el-input v-model="eventForm.outputData" type="textarea" :rows="3" placeholder="请输入输出参数（JSON格式）" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="eventForm.description" type="textarea" :rows="3" placeholder="请输入描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="eventDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveEvent">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 服务编辑对话框 -->
  <el-dialog
    :title="serviceForm.id ? '编辑服务' : '新增服务'"
    v-model="serviceDialogVisible"
    width="600px"
    append-to-body
  >
    <el-form ref="serviceFormRef" :model="serviceForm" :rules="serviceRules" label-width="100px">
      <el-form-item label="标识符" prop="identifier">
        <el-input v-model="serviceForm.identifier" placeholder="请输入标识符" />
      </el-form-item>
      <el-form-item label="服务名称" prop="name">
        <el-input v-model="serviceForm.name" placeholder="请输入服务名称" />
      </el-form-item>
      <el-form-item label="调用方式" prop="callType">
        <el-select v-model="serviceForm.callType" placeholder="请选择调用方式" style="width: 100%">
          <el-option label="同步" value="sync" />
          <el-option label="异步" value="async" />
        </el-select>
      </el-form-item>
      <el-form-item label="输入参数" prop="inputData">
        <el-input v-model="serviceForm.inputData" type="textarea" :rows="3" placeholder="请输入输入参数（JSON格式）" />
      </el-form-item>
      <el-form-item label="输出参数" prop="outputData">
        <el-input v-model="serviceForm.outputData" type="textarea" :rows="3" placeholder="请输入输出参数（JSON格式）" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="serviceForm.description" type="textarea" :rows="3" placeholder="请输入描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="serviceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveService">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props
interface Props {
  visible: boolean
  productId?: string
}

const props = withDefaults(defineProps<Props>(), {
  productId: ''
})

// Emits
const emit = defineEmits(['update:visible', 'save'])

// 响应式数据
const activeTab = ref('properties')
const properties = ref([])
const events = ref([])
const services = ref([])

// 属性表单
const propertyDialogVisible = ref(false)
const propertyFormRef = ref()
const propertyForm = reactive({
  id: '',
  identifier: '',
  name: '',
  dataType: '',
  accessMode: '',
  unit: '',
  range: '',
  description: ''
})

// 事件表单
const eventDialogVisible = ref(false)
const eventFormRef = ref()
const eventForm = reactive({
  id: '',
  identifier: '',
  name: '',
  eventType: '',
  outputData: '',
  description: ''
})

// 服务表单
const serviceDialogVisible = ref(false)
const serviceFormRef = ref()
const serviceForm = reactive({
  id: '',
  identifier: '',
  name: '',
  callType: '',
  inputData: '',
  outputData: '',
  description: ''
})

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单验证规则
const propertyRules = reactive({
  identifier: [{ required: true, message: '标识符不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '功能名称不能为空', trigger: 'blur' }],
  dataType: [{ required: true, message: '数据类型不能为空', trigger: 'change' }],
  accessMode: [{ required: true, message: '读写类型不能为空', trigger: 'change' }]
})

const eventRules = reactive({
  identifier: [{ required: true, message: '标识符不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '事件名称不能为空', trigger: 'blur' }],
  eventType: [{ required: true, message: '事件类型不能为空', trigger: 'change' }]
})

const serviceRules = reactive({
  identifier: [{ required: true, message: '标识符不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '服务名称不能为空', trigger: 'blur' }],
  callType: [{ required: true, message: '调用方式不能为空', trigger: 'change' }]
})

// 工具方法
const getDataTypeTag = (dataType: string) => {
  const tagMap: Record<string, string> = {
    'int': 'primary',
    'float': 'success',
    'bool': 'warning',
    'text': 'info',
    'enum': 'danger',
    'date': 'primary'
  }
  return tagMap[dataType] || 'info'
}

const getAccessModeTag = (accessMode: string) => {
  const tagMap: Record<string, string> = {
    'r': 'info',
    'w': 'warning',
    'rw': 'success'
  }
  return tagMap[accessMode] || 'info'
}

const getAccessModeText = (accessMode: string) => {
  const textMap: Record<string, string> = {
    'r': '只读',
    'w': '只写',
    'rw': '读写'
  }
  return textMap[accessMode] || accessMode
}

const getEventTypeTag = (eventType: string) => {
  const tagMap: Record<string, string> = {
    'info': 'info',
    'alert': 'warning',
    'error': 'danger'
  }
  return tagMap[eventType] || 'info'
}

const getEventTypeText = (eventType: string) => {
  const textMap: Record<string, string> = {
    'info': '信息',
    'alert': '告警',
    'error': '故障'
  }
  return textMap[eventType] || eventType
}

// 属性操作
const handleAddProperty = () => {
  resetPropertyForm()
  propertyDialogVisible.value = true
}

const handleEditProperty = (row: any) => {
  // 深拷贝并处理数据
  Object.assign(propertyForm, processPropertyData({ ...row }))
  propertyDialogVisible.value = true
}

const handleDeleteProperty = (index: number) => {
  ElMessageBox.confirm('确定要删除这个属性吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    properties.value.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

const handleSaveProperty = () => {
  propertyFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (propertyForm.id) {
        // 编辑
        const index = properties.value.findIndex((item: any) => item.id === propertyForm.id)
        if (index !== -1) {
          properties.value[index] = { ...propertyForm }
        }
      } else {
        // 新增
        propertyForm.id = Date.now().toString()
        properties.value.push({ ...propertyForm })
      }
      propertyDialogVisible.value = false
      ElMessage.success('保存成功')
    }
  })
}

// 处理属性数据
const processPropertyData = (data: any) => {
  const processed = { ...data }
  // 将空字符串转换为undefined，避免select组件显示选择状态
  Object.keys(processed).forEach(key => {
    if (processed[key] === '') {
      processed[key] = undefined
    }
  })
  return processed
}

// 处理事件数据
const processEventData = (data: any) => {
  const processed = { ...data }
  Object.keys(processed).forEach(key => {
    if (processed[key] === '') {
      processed[key] = undefined
    }
  })
  return processed
}

// 处理服务数据
const processServiceData = (data: any) => {
  const processed = { ...data }
  Object.keys(processed).forEach(key => {
    if (processed[key] === '') {
      processed[key] = undefined
    }
  })
  return processed
}

const resetPropertyForm = () => {
  Object.assign(propertyForm, {
    id: '',
    identifier: '',
    name: '',
    dataType: undefined,
    accessMode: undefined,
    unit: '',
    range: '',
    description: ''
  })
}

// 事件操作
const handleAddEvent = () => {
  resetEventForm()
  eventDialogVisible.value = true
}

const handleEditEvent = (row: any) => {
  // 深拷贝并处理数据
  Object.assign(eventForm, processEventData({ ...row }))
  eventDialogVisible.value = true
}

const handleDeleteEvent = (index: number) => {
  ElMessageBox.confirm('确定要删除这个事件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    events.value.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

const handleSaveEvent = () => {
  eventFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (eventForm.id) {
        // 编辑
        const index = events.value.findIndex((item: any) => item.id === eventForm.id)
        if (index !== -1) {
          events.value[index] = { ...eventForm }
        }
      } else {
        // 新增
        eventForm.id = Date.now().toString()
        events.value.push({ ...eventForm })
      }
      eventDialogVisible.value = false
      ElMessage.success('保存成功')
    }
  })
}

const resetEventForm = () => {
  Object.assign(eventForm, {
    id: '',
    identifier: '',
    name: '',
    eventType: undefined,
    outputData: '',
    description: ''
  })
}

// 服务操作
const handleAddService = () => {
  resetServiceForm()
  serviceDialogVisible.value = true
}

const handleEditService = (row: any) => {
  // 深拷贝并处理数据
  Object.assign(serviceForm, processServiceData({ ...row }))
  serviceDialogVisible.value = true
}

const handleDeleteService = (index: number) => {
  ElMessageBox.confirm('确定要删除这个服务吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    services.value.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

const handleSaveService = () => {
  serviceFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (serviceForm.id) {
        // 编辑
        const index = services.value.findIndex((item: any) => item.id === serviceForm.id)
        if (index !== -1) {
          services.value[index] = { ...serviceForm }
        }
      } else {
        // 新增
        serviceForm.id = Date.now().toString()
        services.value.push({ ...serviceForm })
      }
      serviceDialogVisible.value = false
      ElMessage.success('保存成功')
    }
  })
}

const resetServiceForm = () => {
  Object.assign(serviceForm, {
    id: '',
    identifier: '',
    name: '',
    callType: undefined,
    inputData: '',
    outputData: '',
    description: ''
  })
}

// 主对话框操作
const handleSave = () => {
  const thingModel = {
    properties: properties.value,
    events: events.value,
    services: services.value
  }
  emit('save', thingModel)
  ElMessage.success('物模型保存成功')
}

const handleCancel = () => {
  emit('update:visible', false)
}

const handleClose = () => {
  emit('update:visible', false)
  // 只在新增模式下重置表单，编辑模式下保留数据
  if (!props.data) {
    resetPropertyForm()
    resetEventForm()
    resetServiceForm()
  }
  // 清除验证状态
  propertyFormRef.value?.clearValidate()
  eventFormRef.value?.clearValidate()
  serviceFormRef.value?.clearValidate()
}

// 监听对话框显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      activeTab.value = 'properties'
      if (props.data) {
        // 编辑模式：加载物模型数据
        loadThingModel()
      } else {
        // 新增模式：重置所有表单
        resetPropertyForm()
        resetEventForm()
        resetServiceForm()
        // 清空列表数据
        properties.value = []
        events.value = []
        services.value = []
      }
    }
  }
)

// 监听数据变化
watch(
  () => props.data,
  (newData) => {
    if (props.visible && newData) {
      loadThingModel()
    }
  },
  { immediate: true, deep: true }
)

// 加载物模型数据
const loadThingModel = () => {
  // 模拟数据
  properties.value = [
    {
      id: '1',
      identifier: 'temperature',
      name: '温度',
      dataType: 'float',
      accessMode: 'r',
      unit: '°C',
      range: '-40~85',
      description: '环境温度'
    },
    {
      id: '2',
      identifier: 'humidity',
      name: '湿度',
      dataType: 'float',
      accessMode: 'r',
      unit: '%',
      range: '0~100',
      description: '环境湿度'
    }
  ]
  
  events.value = [
    {
      id: '1',
      identifier: 'alarm',
      name: '告警事件',
      eventType: 'alert',
      outputData: '{"level": "high", "message": "温度过高"}',
      description: '温度超过阈值时触发'
    }
  ]
  
  services.value = [
    {
      id: '1',
      identifier: 'reset',
      name: '重置设备',
      callType: 'async',
      inputData: '{}',
      outputData: '{"result": "success"}',
      description: '重置设备到出厂设置'
    }
  ]
}
</script>

<style scoped>
.tab-header {
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>